package Web.Servlet;

import Domain.Comment;
import Domain.User;
import Service.CommentService;
import Service.Impl.CommentServiceImpl;
import Service.Impl.UserServiceImpl;
import Service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@WebServlet("/CommentServlet")
public class CommentServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("utf-8");
        String action = request.getParameter("action");
        System.out.println("CommentServlet Running");
        if(action.equals("AddComment")){
            String uid = request.getParameter("uid");
            String pid = request.getParameter("pid");

            String newmsg = request.getParameter("newmsg");
            String picture = request.getParameter("picture");

            Date date = new Date();

            Comment comment = new Comment();
            comment.setUserid(Integer.parseInt(uid));
            comment.setProductid(Integer.parseInt(pid));
            comment.setNewmsg(newmsg);
            comment.setPicture(picture);
            comment.setNewtime(date);
            CommentService service = new CommentServiceImpl();
            service.AddComment(comment);

            request.getRequestDispatcher("Comment/CommentSuccess.jsp").forward(request,response);

        }

        if(action.equals("DelComment")){
            String uid = request.getParameter("uid");
            UserService service = new UserServiceImpl();
            List<User> list = service.findUserById(Integer.parseInt(uid));
            User user = list.get(0);

            String id = request.getParameter("id");
            String pid = request.getParameter("pid");
            CommentService service1 = new CommentServiceImpl();
            service1.DelComment(Integer.parseInt(id));

            request.setAttribute("user",user);

            response.sendRedirect(request.getContextPath()+"/ProductServlet?action=IntoProduct&uid="+user.getId()+"&pid="+pid);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
